//
//  LPWKHasCommentAndHeadLineViewController.m
//  LovingPartyBuilding
//
//  Created by 刘应平 on 2017/6/1.
//  Copyright © 2017年 刘应平. All rights reserved.
//

#import "LPWKHasCommentAndHeadLineViewController.h"
#import "WKWebView+LPWKShowBigImageView.h"
#import "LPNewsCommentCoustomView.h"
#import "SendCommentView.h"
#import <IQKeyboardManager.h>
#import "ZJShareManager.h"
#import "LPWKNewsCommentListViewController.h"
#import "STPhotoBroswer.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import "FuncationCreatingLivingViewController.h"
@interface LPWKHasCommentAndHeadLineViewController ()<UIWebViewDelegate,LPNEWSCommentCoustomDelegate,SendCommentViewDelegate>{
    UIView *_commentBGView;/** 评论页面背景View */
}
/**  wkwebView  */
@property (strong, nonatomic) UIWebView  *webView;
/**  评论  */
//@property (strong, nonatomic) LPNewsCommentCoustomView  *comment;
/** 评论模块 */
@property (nonatomic, strong) SendCommentView *sendCommentView;
/**  显示view  */
@property (strong, nonatomic) STPhotoBroswer  *brower;

@end

@implementation LPWKHasCommentAndHeadLineViewController

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = NO;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.titlelabel.text = self.model.TITLE;
    [self.view addSubview:self.webView];
//    [self.view addSubview:self.comment];
    
    
    
//    _commentBGView = [[UIView alloc] initWithFrame:self.view.bounds];
//    _commentBGView.backgroundColor = [UIColor blackColor];
//    _commentBGView.alpha = 0.2;
//    _commentBGView.hidden = YES;
//    UITapGestureRecognizer *tapGester = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(action_tapGester)];
//    [_commentBGView addGestureRecognizer:tapGester];
//    [self.view addSubview:_commentBGView];
//    [self.view addSubview:self.sendCommentView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];/**< 键盘将要出现的通知 */
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillDismiss:) name:UIKeyboardWillHideNotification object:nil];/**< 键盘将要消失的通知 */
    
    [YJProgressHUD showMessage:@"加载中..." duration:10 view:self.view];
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.model.URL]]];
}

- (UIWebView *)webView{
    if (!_webView) {
        _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, LP_TopHeight, self.view.width, self.view.height - LP_TopHeight )];
        _webView.delegate = self;
        _webView.dataDetectorTypes = UIDataDetectorTypeAll;
        _webView.backgroundColor = [UIColor clearColor];
        [_webView setOpaque:YES];
    }
    return _webView;
}


- (void)webViewDidFinishLoad:(UIWebView *)webView{
    [YJProgressHUD hide];
    //js代码
    NSString *jsString =
    @"(function(){"
    "var objs = document.getElementsByTagName('img');"
    "var imgReqs = '';"
    "for(var i=0,j=0;i<objs.length;i++)"
    "{"
        "var levelcode = objs[i].getAttribute('levelcode');"
        "var path = objs[i].getAttribute('src');"
        "if(levelcode=='-1'){"
            "continue;"
        "}"
        "if(imgReqs){imgReqs += (','+path);}"
        "else imgReqs = path;"
        "objs[i].setAttribute('index',j);"
        "j++;"
        "objs[i].onclick=function()"
        "{"
            "var index = this.getAttribute('index');"
            "openImage(index,imgReqs);"
        "}"
    "}"
    "})()";
    
    __weak typeof(self) weakSelf = self;
    [webView stringByEvaluatingJavaScriptFromString:jsString];
    //其中 openImage 是JS的函数名，得到的 arg数组 里面为JS的 passValue 函数的参数，即 JS要传给OC的参数。
    JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    
    context[@"openImage"] = ^(){
        NSMutableArray *images = [NSMutableArray array];
        NSArray *infor = [JSContext currentArguments];
        JSValue *index = infor.firstObject;
        JSValue *imageString = infor.lastObject;
        NSString *indexString = [index toString];
        NSString *string = [imageString toString];
        
        if ([string containsString:@","]) {
            NSArray *array = [string componentsSeparatedByString:@","];
            [images addObjectsFromArray:array];
        }else{
            [images addObject:string];
        }
        
         NSMutableArray *imageStirngs = [NSMutableArray array];
        NSString *firstImageString = [images objectAtIndex:0];
        if ([firstImageString containsString:@"http"]) {
            for (NSString *imageString in images) {
                NSMutableString *mutale = [[NSMutableString alloc] initWithString:imageString];
                

               
                NSString *getString = [mutale stringByReplacingOccurrencesOfString:BASEIMAGEURL withString:@""];
                
                [imageStirngs addObject:getString];
            }

        }else{
        
            for (NSString *imageString in images) {
                NSString *string = [imageString substringFromIndex:11];
                
                [imageStirngs addObject:string];
            }
        }
       
        
        dispatch_async(dispatch_get_main_queue(), ^{
            weakSelf.brower = [[STPhotoBroswer alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height) ImageArray:imageStirngs currentIndex:[indexString integerValue]];
            [weakSelf.brower show];
        });
    };

}

#pragma mark - 键盘处理

- (void)action_tapGester{
    [self.view endEditing:YES];
    
}

- (void)keyboardWillShow:(NSNotification *)notification {
    _commentBGView.hidden = NO;
    self.sendCommentView.hidden = NO;
    [self.view bringSubviewToFront:self.sendCommentView];
    
    CGFloat curkeyBoardHeight = [[[notification userInfo] objectForKey:@"UIKeyboardBoundsUserInfoKey"] CGRectValue].size.height;
    
    NSTimeInterval interal = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    //计算 视图应该移动的位置
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:interal animations:^{
        
        weakSelf.sendCommentView.frame = CGRectMake(0, [UIScreen zj_screenHeight] - weakSelf.sendCommentView.height - curkeyBoardHeight, [UIScreen zj_screenWith], weakSelf.sendCommentView.height);
    }];
}

- (void)keyboardWillDismiss:(NSNotification *)notification {
    _commentBGView.hidden = YES;
    self.sendCommentView.hidden = YES;
    NSTimeInterval interal = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    //计算 视图应该移动的位置
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:interal animations:^{
        weakSelf.sendCommentView.frame = CGRectMake(0, [UIScreen zj_screenHeight], [UIScreen zj_screenWith], weakSelf.sendCommentView.height);
        
    }];
}


#pragma mark - SendCommentViewDelegate
- (void)sendButtonClick{
    if (self.sendCommentView.commentTextView.textView.text.length == 0) {
        [YJProgressHUD showMessage:@"请输入评论内容" inView:self.view];
        return;
    }
    __weak typeof(self) weakSelf = self;
    NSMutableDictionary *paramer = [NSMutableDictionary dictionary];
    paramer[@"USERID"] = ZJUSERINFORMODEL.CURRENT_USER_MODEL.ID;
    paramer[@"COURSEWAREID"] = self.model.ID;
    paramer[@"ACCOUNTID"] = ZJUSERINFORMODEL.ORG_ACCOUNT.ID;
    paramer[@"CONTENT"] = self.sendCommentView.commentTextView.textView.text;
    paramer[@"UNITID"] = ZJUSERINFORMODEL.CURRENT_DEPT_MODEL.ID;
    paramer[@"FID"] = @"";
    paramer[@"VIDEOSTAMP"] = @"111111";
    paramer[@"REVIEWTYPE"] = @"1";
    [NetWorkingManager postWithUrlString:[NetWorkingURL addClassFAQ] Parameter:paramer Success:^(id object) {
        if ([object[@"STATE"] isEqualToString:@"20000"]) {
            [YJProgressHUD showMsgWithoutView:@"评论成功"];
            [weakSelf.view endEditing:YES];
        }else{
            [YJProgressHUD showMsgWithoutView:@"评论失败"];
        }
    } Fail:^(id object) {
        [YJProgressHUD showMsgWithoutView:@"评论失败"];
    }];

}

#pragma mark - LPNEWSCommentCoustomDelegate
- (void)LPNEWSCommentCoustomViewDelegate_commentTextButtonClick{
//    self.sendCommentView.hidden = NO;
//    [self.sendCommentView.commentTextView.textView becomeFirstResponder];
    FuncationCreatingLivingViewController *vc = [FuncationCreatingLivingViewController new];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)LPNEWSCommentCoustomWithView:(LPNewsCommentCoustomView *)view commentButtonClick:(NSInteger)buttonTag{
    if (buttonTag == 0) {
        /**  跳转评论列表  */
//        LPWKNewsCommentListViewController *vc = [LPWKNewsCommentListViewController new];
//        vc.model = self.model;
//        vc.titleString = @"评论列表";
//        [self.navigationController pushViewController:vc animated:YES];
        FuncationCreatingLivingViewController *vc = [FuncationCreatingLivingViewController new];
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        /**  分享  */
//        ZJShareManager *shareManager = [[ZJShareManager alloc] init];
//        ZJShareModel *shareModel = [ZJShareModel new];
//        shareModel.thumImage = [UIImage imageNamed:@""];
//        shareModel.title = @"分享";
//        shareModel.descr = @"分享fenfenfenfnefnenfn";
//        shareModel.webpageUrl = @"www.baidu.com";
//        shareManager.shareModel = shareModel;
//        [shareManager show];
        [YJProgressHUD showSuccess:@"暂无该功能" inview:self.view];

    }
   
}

//- (LPNewsCommentCoustomView *)comment{
//    if (!_comment) {
//        _comment = [[LPNewsCommentCoustomView alloc] initWithFrame:CGRectMake(0, self.view.height - 49, self.view.width, 49) titles:@[@"评论",@"分享"] images:@[@"tab_comment",@"tab_share"]];
//        _comment.delegate = self;
//    }
//    return _comment;
//}

- (SendCommentView *)sendCommentView{
    if (_sendCommentView == nil){
        _sendCommentView = [[SendCommentView alloc]initWithFrame:CGRectMake(0, [UIScreen zj_screenHeight], [UIScreen zj_screenWith], [UIScreen zj_screenHeight] * 0.2)];
        _sendCommentView.commentDelegate = self;
    }
    return _sendCommentView;
}


@end
